import React from "react";
import DoubleInput from "../DoubleInput";
import { GridConsumer } from "context/useGridContext";
import "./index.less";

/**
 *
 * @param {info} 宫格的相关奖品信息
 * @param {location} 宫格的所在索引
 * @returns
 */
export default function GridItem({ info, location }) {
  // 拖拽元素时候触发
  const onDragOver = (e) => {
    e.preventDefault();
  };
  //  在一个拖动过程中，释放鼠标键时触发此事件
  const onDrop = (e, updateGridHandler) => {
    // 从拖拽事件中获取传输过来的数据
    const info = JSON.parse(e.dataTransfer.getData("info"));
    info.prob = 0;
    info.releaseProb = 0;
    updateGridHandler(info, location);
  };
  return (
    <GridConsumer>
      {({ updateGridHandler, updateGridValue }) => {
        return (
          <div
            className="grid-item"
            onDrop={(e) => onDrop(e, updateGridHandler)}
            onDragOver={onDragOver}
          >
            {/* 判断是否有奖品在九宫格中 */}
            {Object.keys(info).length ? (
              <>
                <img className="grid-img" src={info.imgPath} alt="img" />
                {/* 修改奖品名展示组件 */}
                <DoubleInput
                  name="奖品名"
                  value={info.title}
                  location={location}
                  referType="title"
                  updateGridValue={updateGridValue}
                />
                {/* 概率展示组件 */}
                <DoubleInput
                  name="概率"
                  value={info.prob}
                  location={location}
                  referType="prob"
                  updateGridValue={updateGridValue}
                  inputType="number"
                />
                {/* 开大奖概率展示组件 */}
                <DoubleInput
                  name="开奖概率"
                  value={info.releaseProb}
                  location={location}
                  referType="releaseProb"
                  updateGridValue={updateGridValue}
                  inputType="number"
                />
              </>
            ) : (
              <span className="grid-tool">等待添加</span>
            )}
          </div>
        );
      }}
    </GridConsumer>
  );
}
